from flask import Blueprint, request
# 引入 User 数据库
from flask_demo.entities import User
from flask_demo import app_database
user_blue_print = Blueprint("user_blue_print", __name__, url_prefix="/user")


@user_blue_print.route("/abc", methods=["get", ])
def get_user():
    return "ABC"


# @user_blue_print.route("/get_id")
# def get_user_abc():
#     id = request.args.get("id")
#     return "your id is " + str(id)


@user_blue_print.route("/login", methods=["post", ])
def post_user_login():
    username = request.json.get("username")
    password = request.json.get("password")
    print("request: post_user_login: ", username, password)
    success = False
    role = 1
    user_id = -1
    try:
        u = User.query.filter_by(username=username).first()
        if u is not None:
            if u.password == password:
                success = True
                role = u.role
                user_id = u.user_id
                pass
            pass
    except:
        print("Error: post_user_login: ")
    return {
        "success": success,
        "data": {
            "username": username,
            "role": role,
            "user_id": user_id
        }
    }


@user_blue_print.route("/all", methods=["get", ])
def get_user_all():
    user_list = User.query.all()
    return {
        "success": True,
        "data": {
            "dataList": [i.to_dict() for i in user_list]
        },
    }


@user_blue_print.route("/set_manager", methods=["post", ])
def post_user_set_manager():
    return {
        "ok": True,
    }


@user_blue_print.route("/cancel_manager", methods=["post",])
def post_user_cancel_manager():
    return {
        "ok": True
    }


@user_blue_print.route("/delete", methods=["post", ])
def post_user_delete():
    return {
        "ok": True
    }


@user_blue_print.route("/new", methods=["post", ])
def post_user_new():
    success = False
    username = request.json.get("username")
    password = request.json.get("password")
    try:
        u = User(username=username, password=password, role=1)
        app_database.session.add(u)
        app_database.session.commit()
        success = True
        pass
    except:
        success = False
        pass
    return {
        "success": success
    }